package org.example.springbootpra1.demos.Filter;

import com.auth0.jwt.interfaces.Claim;
import org.example.springbootpra1.demos.util.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "JwtFilter", urlPatterns = "/api/user/secure/*")
public class JwtFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        response.setCharacterEncoding("UTF-8");

        final String token = request.getHeader("Auth");

        if("OPTIONS".equals(request.getMethod())) { // 是否是 OPTIONS 请求
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        }
        else {

            if(token == null) {
                response.getWriter().write("no token");
                return;
            }
            Map<String, Claim> userData = JwtUtils.verifyToken(token); // 检验 token
            if(userData == null) {
                response.getWriter().write("token illegal");
                return;
            }

            Integer id = userData.get("id").asInt(); // 获取 id
            String userName = userData.get("userName").asString(); // 获取用户名
            String password = userData.get("password").asString(); // 获取密码
            request.setAttribute("id", id); // 设置 id
            request.setAttribute("userName", userName); // 设置用户名
            request.setAttribute("password", password); // 设置密码

            chain.doFilter(req, res); // 过滤成功
        }
    }

    @Override
    public  void destroy() {}

}
